#include "random.h"

void random_init()
{
	AES.CTRL = AES_RESET_bm;
	
	AES.KEY = PRODSIGNATURES_LOTNUM0;
	AES.KEY = PRODSIGNATURES_LOTNUM1;
	AES.KEY = PRODSIGNATURES_LOTNUM2;
	AES.KEY = PRODSIGNATURES_LOTNUM3;

	AES.KEY = PRODSIGNATURES_LOTNUM4;
	AES.KEY = PRODSIGNATURES_LOTNUM5;
	AES.KEY = PRODSIGNATURES_WAFNUM;
	AES.KEY = PRODSIGNATURES_COORDX0;
	
	AES.KEY = PRODSIGNATURES_COORDX1;
	AES.KEY = PRODSIGNATURES_COORDY0;
	AES.KEY = PRODSIGNATURES_COORDY1;
	AES.KEY = ADCA.CH0.RESL;

	AES.KEY = ADCA.CH1.RESL;
	AES.KEY = ADCA.CH2.RESL;
	AES.KEY = ADCB.CH0.RESL;
	AES.KEY = ADCB.CH1.RESL;	
	
	r_round = 1;
	
	for (uint8_t i = 0; i < 16; i++) AES.STATE = r_round;
	
	AES.CTRL = AES_START_bm | AES_XOR_bm;
	
	r_position = 0;
}

uint8_t rand_byte()
{
	uint8_t r;
	if (r_position == 0) while (!(AES.STATUS & AES_SRIF_bm));
	r = AES.STATE;
	r_position++;
	if (r_position > 15)
	{
		for (uint8_t i = 0; i < 16; i++) AES.STATE = r_round;
		AES.CTRL = AES_START_bm | AES_XOR_bm;
		r_position = 0;
	}
	return r;
}